var form = layui.form, laydate = layui.laydate, deleteIds = [], upload = layui.upload, table = layui.table, $ = layui.jquery, id = getQueryVariable("id"),isInitData=[];
layui.use(['tableEdit'], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer;

    //附件
    let annexList = [];
    //明细数据
    let detailList = [];
    //收款类型
    let paymentTypeList = [];
    //操作日志数据
    let operationLog = [];

    //修改前主表银行扣费外
    let oldBankDeductionExcept = 0;

    $(document).ready(function () {

        getDetailInfo();
        table.reload('claimdetailtableid',{data : detailList, limit : detailList.length});
        table.reload('attachmenttableid',{data : annexList});
        table.reload('logtableid',{data:operationLog});
    });

  function getDetailInfo(){
      //获取详情信息
      $.ajax({
          url:"receivePayment/detail?id="+id +"&type=0",
          async: false,
          success:function(res){
              if(res.status == 200){
                  //主表信息赋值
                  let vo =  res.data;
                  oldBankDeductionExcept = vo.bankDeductionExcept;
                  form.val("editor-form", {
                      "id" : vo.id,
                      "billNo" : vo.billNo,
                      "time" : vo.time,
                      "customerName" : vo.customerName,
                      "accountName" : vo.accountName,
                      "currency" : vo.currency,
                      "currencyCode":vo.currencyCode,
                      "rmbRate" : vo.rmbRate,
                      "usdRate" : vo.usdRate,
                      "entryAmount" : vo.entryAmount,
                      "bankDeductionExcept" : vo.bankDeductionExcept,
                      "bankDeductionCapital" : vo.bankDeductionCapital,
                      "collectionAmount" : vo.collectionAmount,
                      "claimed" : vo.claimed,
                      "toBeClaimed" : vo.toBeClaimed,
                      "salesman" : vo.salesman,
                      "voucherCompanyName" : vo.voucherCompanyName,
                      "operator" : vo.operator,
                      "memo" : vo.memo
                  });

                  //明细数据信息
                  if(null != vo.detailList && vo.detailList.length > 0){
                      let tempData = vo.detailList;
                      //生成临时id
                      for(let i in tempData){
                          let tempId = GenNonDuplicateID(3) + (i+1);
                          tempData[i].tempId = tempId;
                          detailList.push(tempData[i]);
                          isInitData.push(tempId);
                      }
                  }

                  //附件信息信息
                  if(null != vo.annexList && vo.annexList.length > 0){
                      annexList = vo.annexList;
                  }

                  //日志
                  if(!isEmpty(res.data.logList) && res.data.logList.length > 0){
                      operationLog = res.data.logList;
                  }

                  return false;
              }else {
                  layer.msg(res.msg, {icon: 5});
              }
          }
      });
      form.render();

      //获取收款类型
      $.ajax({
          url:"receivePayment/getReceivePaymentTypeInfo",
          async: false,
          success:function(data){
              if(data.status == 200){
                  paymentTypeList = data.data;
              }
          }
      });
  }

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    $('#editor-form').find('input,textarea,select').attr('disabled', true);
    //表单初始值
    if (id != "") {
        form.val("editor-form", {
            "receiptnumber": "初始值",
        })
    }
    //监听提交
    form.on('submit(form-element)', function (data) {
        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        //获取明细数据
        let number = 0;
        let detailList = table.cache["claimdetailtableid"];
        //明细国外银行扣费
        let detailForeignBankDeductions = 0;
        let billType = false;
        $.each(detailList, function (index, value) {
            if (typeof (detailList[index]["collectionAmount"]) == "undefined" || detailList[index]["collectionAmount"] == "") {
                layer.msg("认领明细表第" + (index + 1) + "条收汇金额不能为空");
                number++;
                return false;
            } else if (typeof (detailList[index]["amountClaimed"]) == "undefined" || detailList[index]["amountClaimed"] == "") {
                layer.msg("认领明细表第" + (index + 1) + "条认领金额不能为空");
                number++;
                return false;
            }
            if(typeof (detailList[index]["invoiceNumber"]) == "undefined" || detailList[index]["invoiceNumber"] == ""){
                billType = true;
            }
            let tempForeignBankDeductions = detailList[index]["foreignBankDeductions"];
            detailForeignBankDeductions = new BigNumber(tempForeignBankDeductions).plus(detailForeignBankDeductions);
        });
        //待认领
        let toBeClaimed = req["toBeClaimed"];
        if(isEmpty(toBeClaimed) && billType){
            let bankDeductionExcept = req["bankDeductionExcept"];
            let flag = new BigNumber(bankDeductionExcept).comparedTo(detailForeignBankDeductions) === 0;
            if(!flag){
                layer.msg("请填写银行扣费");
                number++;
                return false;
            }
        }
        if (number == 0) {

            //防止重复提交问题
            preventDuplicateSubmissions();

            req["detailList"] = detailList;

            //获取附件数据
            let annexReqs = table.cache["attachmenttableid"];

            req["annexList"] = annexReqs;

            //被删除的明细id
            req["deleteIds"] = deleteIds;

            let datas = JSON.stringify(req);
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:datas,
                url:"receivePayment/collectionClaimAdd",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("保存成功", {icon: 6});
                        parent.table.reload('maininformationtableid');
                        setTimeout(function () {
                            let index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                        },);
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                    return false;
                }
            });
        }
    });

    //--认领明细
    table.render({
        elem: '#claimdetail',
        id: 'claimdetailtableid',
        data: detailList,
        toolbar: '#claimdetailtoolbar',
        totalRow: true,
        cols: [[
            {checkbox: true},
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'invoiceNumber', width: 120, title: '发票编号', sort: true},
            {field: 'contractNo', width: 120, title: '合同编号', sort: true},
            {field: 'typeCode', width: 120, title: '收款类型' , templet: '#typeCodeSelect'},
            {field: 'collectionAmount', width: 120, title: '收汇金额', edit: 'text', totalRow: true},
            {field: 'foreignBankDeductions', width: 120, title: '国外银行扣费', edit: 'text', event: 'foreignBankDeductions', totalRow: true},
            {field: 'domesticBankCharge', width: 120, title: '国内银行扣费', edit: 'text', totalRow: true},
            {field: 'amountClaimed', width: 120, title: '认领金额', totalRow: true},
            {field: 'allocatedAmount', width: 120, title: '已分摊金额', sort: true, totalRow: true},
            {field: 'unallocatedAmount', width: 120, title: '未分摊金额', sort: true, totalRow: true},
            {field: 'totalContract', width: 120, title: '合同总额', sort: true, totalRow: true},
            {field: 'totalInvoice', width: 120, title: '发票总额', sort: true, totalRow: true},
            {field: 'contractUnclaimedAmount', width: 150, title: '合同未认领金额', edit: 'text', totalRow: true},
            {field: 'refundAmount', width: 120, title: '退款金额', edit: 'text', totalRow: true},
            {field: 'claimDate', width: 120, title: '认领日期', templet:function(d){
                    return '<input type="text" value="'+d.claimDate+'"  class="layui-input layui-input-date">';
                }},
            {field: 'claimCustomer', width: 120, title: '认领客户', edit: 'text'},
            {field: 'claimSalesman', width: 120, title: '认领业务员', edit: 'text'},
            {field: 'memo', width: 120, title: '备注', edit: 'text'}
        ]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')

            $(".layui-input-date").each((i,e)=>{
                laydate.render({
                    elem:e,
                    format: 'yyyy-MM-dd',
                    type: 'date',
                    trigger: 'click',
                    theme: '#393D49',
                    calendar: true,
                    done(data){
                        let tableData = table.cache["claimdetailtableid"];
                        tableData[i]["claimDate"] = data;
                        table.reload('claimdetailtableid',{data:tableData});
                    }
                });
            })

            for(let i in paymentTypeList){
                $(".paymentType").append("<option value=\"" + paymentTypeList[i].code + "\">" + paymentTypeList[i].name + "</option>");
            }

            //待认领金额
            let toBeClaimed = new BigNumber($("#toBeClaimed").val());
            //已认领
            let claimed = new BigNumber($("#claimed").val());
            let flag = false;
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                $("#paymentType_" + tempId).val(res.data[i].typeCode);

                let fValue = isInitData.indexOf(tempId);
                if(-1 == fValue){

                    //收汇金额
                    let collectionAmount = new BigNumber(res.data[i].collectionAmount);
                    toBeClaimed = toBeClaimed.minus(collectionAmount);
                    //认领金额
                    let amountClaimed = new BigNumber(res.data[i].amountClaimed);
                    claimed = claimed.plus(amountClaimed);

                    flag = true;
                    isInitData.push(tempId);
                }

            }
            if(flag){
                $("#toBeClaimed").val(new BigNumber(toBeClaimed).dp(2, BigNumber.ROUND_HALF_UP).toString());
                $("#claimed").val(new BigNumber(claimed).dp(2, BigNumber.ROUND_HALF_UP).toString());
            }

            form.render();
            // 当前表格渲染之后的视图
            let tableView = this.elem.next();
            layui.each(res.data, function(i, item){
                if(item.confirmed == 1){
                    //已确认数据不能编辑和删除
                    tableView.find('tr[data-index=' + i + ']').css("background-color", "#CCCCCC").find('td').data('edit',false)
                }
            });
        }
    });
    form.on("select(typeCodeSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["claimdetailtableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["typeCode"] = data.value;
                tableData[index]["typeName"] = getTypeName(data.value);
            }
        });
    });
    function getTypeName(code){
        for(let i in paymentTypeList){
            if(paymentTypeList[i].code == code){
                return paymentTypeList[i].name;
            }
        }
        return "";
    }

    function productTableReload(){
        table.reload('claimdetailtableid',{
            data:table.cache.test,
            totalRow: true,
        })
    }

    table.on('edit(claimdetailtable)', function (obj) {
        //旧值
        let oldVal = $(this).prev().text();
        //判断数据类型 ,,,,,,,
        if ((obj.field == "collectionAmount" ||
            obj.field == "foreignBankDeductions" ||
            obj.field == "domesticBankCharge" ||
            obj.field == "amountClaimed" ||
            obj.field == "contractUnclaimedAmount" ||
            obj.field == "refundAmount") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(oldVal);
            return;
        }
        let data = obj.data;
        if(obj.field == "collectionAmount"){
            if(!autoUpdate(obj, data, 1)){
                $(this).val(oldVal);
                obj.update({
                    collectionAmount :  oldVal
                });
                return;
            }
        }else if(obj.field == "foreignBankDeductions"){
            if(!autoUpdate(obj, data, 2)){
                $(this).val(oldVal);
                obj.update({
                    foreignBankDeductions :  oldVal
                });
                return;
            }
        }else if(obj.field == "domesticBankCharge"){
            //获取所有明细数据
            let detailData = table.cache["claimdetailtableid"];
            let sum = 0;
            for(let i in detailData){
                //银行扣费（本） = 明细表中 国内银行扣费总和
                sum = new BigNumber(sum).plus(detailData[i].domesticBankCharge);
            }
            $("#bankDeductionCapital").val(sum.dp(2, BigNumber.ROUND_HALF_UP).toString());
            form.render();
        }

        //表单重载
        productTableReload();
    });

    function autoUpdate(obj, data, type){
        //收汇金额
        let collectionAmount = 0;
        //国外银行扣费
        let foreignBankDeductions = 0;
        if(1 == type){
            collectionAmount = new BigNumber(obj.value);
            //国外银行扣费
            foreignBankDeductions = new BigNumber(data.foreignBankDeductions);
        }else if(2 == type){
            //收汇金额
            collectionAmount = new BigNumber(data.collectionAmount);
            //国外银行扣费
            foreignBankDeductions = new BigNumber(obj.value);
        }

        //认领金额 = 收汇金额-国外银行扣费
        let amountClaimed = new BigNumber(collectionAmount).minus(foreignBankDeductions);
        //获取所有明细数据
        let detailData = table.cache["claimdetailtableid"];
        let sum = 0;
        let tempId = data.tempId;
        //合同编号
        let contractNo = data.contractNo;
        //结汇单号
        let invoiceNumber = data.invoiceNumber;
        //同一合同号认领金额总和
        let sameAmountClaimedSum = 0;
        //同一合同号收汇金额总和
        let sameCollectionAmountSum = 0;
        //同一合同号发票金额总和
        let totalInvoiceSum = 0;
        for(let i in detailData){
            //发票金额
            let totalInvoice = 0;
            if(!isEmpty(detailData[i]["totalInvoice"])){
                totalInvoice = detailData[i]["totalInvoice"];
            }
            if(detailData[i].tempId == tempId){
                sameAmountClaimedSum = new BigNumber(sameAmountClaimedSum).plus(amountClaimed);
                sameCollectionAmountSum = new BigNumber(sameCollectionAmountSum).plus(collectionAmount);
                totalInvoiceSum = new BigNumber(totalInvoiceSum).plus(totalInvoice);
                continue;
            }
            let detailAmountClaimed = new BigNumber(detailData[i].amountClaimed);
            let detailCollectionAmount = new BigNumber(detailData[i].collectionAmount);
            if(contractNo === detailData[i].contractNo){
                //统计同一合同号的收汇金额
                sameCollectionAmountSum = new BigNumber(sameCollectionAmountSum).plus(detailCollectionAmount);
                if(invoiceNumber === detailData[i].invoiceNumber){
                    //统计同一合同号相同结汇的认领金额
                    sameAmountClaimedSum = new BigNumber(sameAmountClaimedSum).plus(detailAmountClaimed);
                    //统计同一合同号的发票金额
                    totalInvoiceSum = new BigNumber(totalInvoiceSum).plus(totalInvoice);
                }
            }
            //主表已认领金额 = 明细中 认领金额总和
            sum = new BigNumber(sum).plus(detailAmountClaimed);

            foreignBankDeductions = new BigNumber(foreignBankDeductions).plus(detailData[i].foreignBankDeductions);
        }
        if(new BigNumber(sameAmountClaimedSum).comparedTo(new BigNumber(0)) == 1 && new BigNumber(sameCollectionAmountSum).comparedTo(new BigNumber(0)) == 1){
            //合同总额
            let totalContract = data.totalContract;
            //发票编号
            let invoiceNumber = data["invoiceNumber"];
            //发票总额
            let totalInvoice = data["totalInvoice"];
            //合同未认领金额
            let contractUnclaimedAmount = data["contractUnclaimedAmount"];
            if(isEmpty(invoiceNumber)){
                //登记预收款时：同一合同收汇总额不能大于(合同总额与合同未收金额两者取最小值)
                //已收款金额
                let amountReceived = data["amountReceived"];
                //未收款金额 = 合同总额-已收款金额
                let unAmountReceived = new BigNumber(totalContract).minus(new BigNumber(amountReceived));
                if(new BigNumber(sameCollectionAmountSum).comparedTo(new BigNumber(unAmountReceived)) == 1){
                    layer.msg("同一合同收汇总额不能大于合同总额", {icon: 5});
                    return false;
                }
            }else {
                //登记账款时：同一合同相同结汇认领总额不能大于(发票总额与合同未认领金额两者取最小值)
                let newAmount = 0;
                if(new BigNumber(totalInvoice).comparedTo(new BigNumber(contractUnclaimedAmount)) == 1){
                    newAmount = contractUnclaimedAmount;
                }else {
                    newAmount = totalInvoice;
                }
                if(new BigNumber(sameAmountClaimedSum).comparedTo(new BigNumber(newAmount)) == 1){
                    layer.msg("同一合同相同结汇认领总额不能大于发票总额", {icon: 5});
                    return false;
                }
            }
        }
        if(2 == type){
            //主表扣费大于明细扣费
            let flag = new BigNumber(oldBankDeductionExcept).comparedTo(new BigNumber(foreignBankDeductions)) == 1;
            if(!flag){
                //更新主表 银行扣费（外）
                $("#bankDeductionExcept").val(foreignBankDeductions.dp(4, BigNumber.ROUND_HALF_UP).toString());
            }else {
                $("#bankDeductionExcept").val(oldBankDeductionExcept);
            }
            //收汇金额 = 入账金额 + 银行扣费（外）
            let entryAmount = $("#entryAmount").val();
            let collectionAmount = new BigNumber(entryAmount).plus(foreignBankDeductions);
            $("#collectionAmount").val(collectionAmount.dp(4, BigNumber.ROUND_HALF_UP).toString());
        }

        //主表收汇金额
        let parentAmount = $("#collectionAmount").val();
        //明细中：认领金额总和不能大于主表 收汇金额
        let newNum = new BigNumber(sum).plus(amountClaimed);
        /*if(new BigNumber(newNum).comparedTo(new BigNumber(parentAmount)) == 1){
            layer.msg("认领金额总和不能大于登记收汇金额", {icon: 5});
            return false;
        }*/

        //未分摊金额 = 认领金额（关联合同，如果关联结汇，默默认为0）
        if(isEmpty(data.invoiceNumber)){
            //关联合同
            data["unallocatedAmount"] = amountClaimed.dp(4, BigNumber.ROUND_HALF_UP).toString();
            obj.data.unallocatedAmount = amountClaimed.dp(4, BigNumber.ROUND_HALF_UP).toString();
        }else {
            //关联结汇
            data["unallocatedAmount"] = "0";
            obj.data.unallocatedAmount = "0";
        }
        data["amountClaimed"] = amountClaimed.dp(4, BigNumber.ROUND_HALF_UP).toString();
        obj.data.amountClaimed = amountClaimed.dp(4, BigNumber.ROUND_HALF_UP).toString();

        obj.update(data);

        for(let i in paymentTypeList){
            $("#paymentType_" + tempId).append("<option value=\"" + paymentTypeList[i].code + "\">" + paymentTypeList[i].name + "</option>");
        }
        $("#paymentType_" + tempId).val(data.typeCode);

        $("#claimed").val(newNum.dp(2, BigNumber.ROUND_HALF_UP).toString());

        //待认领 = 入账金额-已认领金额
        let entryAmount = $("#entryAmount").val();
        let toBeClaimed = new BigNumber(entryAmount).minus(newNum);
        $("#toBeClaimed").val(toBeClaimed.dp(2, BigNumber.ROUND_HALF_UP).toString());
        form.render();
        return true;
    }
    table.on('toolbar(claimdetailtable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        let currencyCode=$("#currencyCode").val();
        let currencyName=$("#currency").val();
        if (isEmpty(currencyCode)||isEmpty(currencyName)){
            return false;
            layer.msg('主单据币种不能为空');
        }
        switch (obj.event) {
            case 'registeradvancepayment':
                layer.open({
                    type: 2,
                    area: ['90%', '90%'],
                    content: 'views/jsp/Money/tpl/registeradvancepayment.jsp?currencyCode='+currencyCode
                });
                break;
            case 'registeredaccounts':
                layer.open({
                    type: 2,
                    area: ['90%', '90%'],
                    content: 'views/jsp/Money/tpl/registeredaccounts.jsp?currencyName='+encodeURI(currencyName),//escape 中文编码
                    success:function () {

                    }
                });
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确认删除？',confirmInfo(3,6) , function (index) {
                        let cbList = table.cache["claimdetailtableid"];
                        //银行扣费（本）
                        let bankDeductionCapital = new BigNumber($("#bankDeductionCapital").val());
                        //银行扣费（外）
                        let bankDeductionExcept = new BigNumber($("#bankDeductionExcept").val());
                        //收汇金额
                        let collectionAmount = new BigNumber($("#collectionAmount").val());
                        //待认领
                        let toBeClaimed = new BigNumber($("#toBeClaimed").val());
                        //已认领
                        let claimed = new BigNumber($("#claimed").val());
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，且该明细数据为待确认时，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId && 0 == cbList[i].confirmed) {
                                    //数据回退
                                    //国内银行扣费
                                    let domesticBankCharge = cbList[i].domesticBankCharge;
                                    bankDeductionCapital = bankDeductionCapital.minus(domesticBankCharge);

                                    //国外银行扣费
                                    let foreignBankDeductions = new BigNumber(cbList[i].foreignBankDeductions);
                                    bankDeductionExcept = bankDeductionExcept.minus(foreignBankDeductions);
                                    collectionAmount = collectionAmount.minus(foreignBankDeductions);

                                    //明细收汇金额
                                    let collectionAmountChild = new BigNumber(cbList[i].collectionAmount);

                                    toBeClaimed = (toBeClaimed.minus(foreignBankDeductions)).plus(collectionAmountChild);

                                    claimed = (claimed.plus(foreignBankDeductions)).minus(collectionAmountChild);

                                    if(!isEmpty(cbList[i]["id"])){
                                        deleteIds.push(cbList[i]["id"]);
                                    }
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        $("#bankDeductionCapital").val(bankDeductionCapital.dp(2, BigNumber.ROUND_HALF_UP).toString());
                        $("#bankDeductionExcept").val(bankDeductionExcept.dp(2, BigNumber.ROUND_HALF_UP).toString());
                        $("#collectionAmount").val(collectionAmount.dp(2, BigNumber.ROUND_HALF_UP).toString());
                        $("#toBeClaimed").val(toBeClaimed.dp(2, BigNumber.ROUND_HALF_UP).toString());
                        $("#claimed").val(claimed.dp(2, BigNumber.ROUND_HALF_UP).toString());
                        table.reload("claimdetailtableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', event:'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        }else if (obj.event === 'fileName'){
            onLineFile(data.filePath);
        }
    });

//---操作日志
    let logData = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: logData
        , cols: [[
              {field: 'operationType', title: '操作类型', fixed: true}
            , {field: 'operationName', title: '操作员'}
            , {field: 'operationTime', title: '操作日期'}
            , {field: 'operationContent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    function isNumber(val) {
        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }
    //生成临时id
    function GenNonDuplicateID(randomLength){
        return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
    }

    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }
});